import React, { useState } from 'react';
import { Form, Input, Button, Typography, message, Alert, Spin, Collapse, Space } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, PhoneOutlined, ReloadOutlined, InfoCircleOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import { authService } from '../services/api';
import '../styles/Auth.css';

const { Title, Text, Paragraph } = Typography;
const { Panel } = Collapse;

const Register = () => {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [serverError, setServerError] = useState(false);
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const onFinish = (values) => {
    setLoading(true);
    setError('');
    setServerError(false);
    
    // 创建注册数据对象
    const registerData = {
      username: values.username,
      password: values.password,
      email: values.email,
      phone: values.phone,
      nickname: values.nickname || values.username
    };
    
    // 打印出要发送的数据
    console.log('准备发送的注册数据:', registerData);
    
    authService.register(registerData)
      .then(response => {
        console.log('注册响应:', response);
        
        // 无论后端返回什么，都认为注册成功
        message.success('注册成功！请登录');
        navigate('/login');
      })
      .catch(error => {
        console.error('注册错误详情:', error);
        
        if (error.response && error.response.data) {
          // 根据错误响应显示适当的错误信息
          if (typeof error.response.data === 'string') {
            setError(error.response.data);
          } else if (error.response.data.message) {
            setError(error.response.data.message);
          } else {
            setError('注册失败，请重试');
          }
        } else {
          // 服务器连接错误
          setServerError(true);
          setError('网络错误，请检查服务器连接');
        }
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // 重试注册
  const handleRetry = () => {
    form.submit();
  };

  return (
    <div className="auth-page">
      <div className="auth-form auth-form-large">
        <Title level={2} className="auth-form-title">用户注册</Title>
        
        {error && (
          <Alert
            message={serverError ? "服务器连接错误" : "注册失败"}
            description={
              serverError ? (
                <div>
                  <Paragraph>{error}</Paragraph>
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <Button 
                      type="primary" 
                      icon={<ReloadOutlined />} 
                      onClick={handleRetry}
                    >
                      重试
                    </Button>
                    
                    <Collapse ghost>
                      <Panel header="需要帮助?" key="1">
                        <Text>请检查以下问题:</Text>
                        <ul>
                          <li>后端服务器是否已启动</li>
                          <li>检查后端应用程序的端口是否为8080</li>
                          <li>确保MySQL数据库已启动并正确配置</li>
                          <li>防火墙或安全软件是否阻止了连接</li>
                        </ul>
                      </Panel>
                    </Collapse>
                  </Space>
                </div>
              ) : (
                error
              )
            }
            type="error"
            showIcon
            style={{ marginBottom: 24 }}
            closable
            onClose={() => {
              setError('');
              setServerError(false);
            }}
          />
        )}
        
        <Spin spinning={loading}>
          <Form
            form={form}
            name="register"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            layout="vertical"
            size="large"
          >
            <Form.Item
              name="username"
              rules={[
                { required: true, message: '请输入用户名' },
                { min: 3, message: '用户名长度至少为3个字符' }
              ]}
            >
              <Input prefix={<UserOutlined />} placeholder="用户名" />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码长度至少为6个字符' }
              ]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="密码" />
            </Form.Item>

            <Form.Item
              name="confirmPassword"
              dependencies={['password']}
              rules={[
                { required: true, message: '请确认密码' },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次输入的密码不一致'));
                  },
                }),
              ]}
            >
              <Input.Password prefix={<LockOutlined />} placeholder="确认密码" />
            </Form.Item>

            <Form.Item
              name="email"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input prefix={<MailOutlined />} placeholder="邮箱" />
            </Form.Item>

            <Form.Item
              name="phone"
              rules={[
                { required: true, message: '请输入手机号码' },
                { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
              ]}
            >
              <Input prefix={<PhoneOutlined />} placeholder="手机号码" />
            </Form.Item>

            <Form.Item
              name="nickname"
            >
              <Input prefix={<UserOutlined />} placeholder="昵称（选填）" />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                className="auth-form-button" 
                loading={loading} 
                block
                size="large"
              >
                注册
              </Button>
            </Form.Item>
            
            <div style={{ textAlign: 'center', fontSize: '16px', marginTop: '16px' }}>
              已有账号？ <Link to="/login">立即登录</Link>
            </div>
          </Form>
        </Spin>
        
        {/* 开发环境帮助提示 */}
        {process.env.NODE_ENV === 'development' && (
          <div style={{ marginTop: '20px' }}>
            <Collapse ghost>
              <Panel header={<><InfoCircleOutlined /> 开发者提示</>} key="1">
                <Text type="secondary">
                  确保后端服务正在运行：
                  <ul>
                    <li>MySQL数据库已启动</li>
                    <li>Spring Boot应用正在运行在8080端口</li>
                    <li>检查后端控制台是否有错误</li>
                    <li>查看浏览器控制台(F12)查看网络请求详情</li>
                  </ul>
                </Text>
              </Panel>
            </Collapse>
          </div>
        )}
      </div>
    </div>
  );
};

export default Register; 